//
//  FExtension.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/1/29.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Photos

// MARK: - 16进制颜色
extension UIColor {
    convenience init(red: Int, green: Int, blue: Int) {
        assert(red >= 0 && red <= 255, "Invalid red component")
        assert(green >= 0 && green <= 255, "Invalid green component")
        assert(blue >= 0 && blue <= 255, "Invalid blue component")
        
        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
    }
    
    convenience init(hex: Int) {
        self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff)
    }
    
    convenience init(hex: Int, alpha: CGFloat) {
        self.init(red: CGFloat((hex >> 16) & 0xff) / 255.0, green: CGFloat((hex >> 8) & 0xff) / 255.0, blue: CGFloat(hex & 0xff) / 255.0, alpha: alpha)
    }
}

// MARK: - 设置button 文字与图片的位置关系
extension UIButton {
    
    @objc func set(image anImage: UIImage?, title: String,
                   titlePosition: UIViewContentMode, additionalSpacing: CGFloat, imageTopMargin: CGFloat, state: UIControlState){
        self.imageView?.contentMode = .center
        self.setImage(anImage, for: state)
        
        positionLabelRespectToImage(title: title, position: titlePosition, spacing: additionalSpacing, imageTopMargin: imageTopMargin)
        
        self.titleLabel?.contentMode = .center
        self.setTitle(title, for: state)
    }
    
    private func positionLabelRespectToImage(title: String, position: UIViewContentMode,
                                             spacing: CGFloat, imageTopMargin: CGFloat) {
        let imageSize = self.imageRect(forContentRect: self.frame)
        let titleFont = self.titleLabel?.font!
        let titleSize = title.size(withAttributes: [NSAttributedStringKey.font: titleFont!])
        
        var titleInsets: UIEdgeInsets
        var imageInsets: UIEdgeInsets
        
        switch (position){
        case .top:
            titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing),
                                       left: -(imageSize.width), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: imageTopMargin, left: 0, bottom: 0, right: -titleSize.width)
        case .bottom:
            titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing),
                                       left: -(imageSize.width), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: imageTopMargin, left: 0, bottom: 0, right: -titleSize.width)
        case .left:
            titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: imageTopMargin, left: 0, bottom: 0,
                                       right: -(titleSize.width * 2 + spacing))
        case .right:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing)
            imageInsets = UIEdgeInsets(top: imageTopMargin, left: 0, bottom: 0, right: 0)
        default:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
        
        self.titleEdgeInsets = titleInsets
        self.imageEdgeInsets = imageInsets
    }
}

// MARK: - 设置VC的导航栏

extension UIViewController: UINavigationControllerDelegate {
    
    enum NavigationState {
        case black
        case white
    }
    
    func setNavigationColor(colorState: NavigationState) {
        self.navigationController?.navigationBar.isTranslucent = false;
        var hexadecimalInteger = 0x222222
        switch colorState {
        case .black: break
            
        case .white:
            hexadecimalInteger = 0xFFFFFF
        }
        self.navigationController?.navigationBar.barTintColor = UIColor(hex: hexadecimalInteger)
    }
    
    func titleLabel(text: String,_ imageName: String?) {
        
        if let name = imageName {
            let button = UIButton(type: .custom)
            button.setTitle(text, for: .normal)
            button.isUserInteractionEnabled = false
            button.setTitleColor(UIColor.white, for: .normal)
            button.setImage(UIImage(named: name), for: .normal)
            button.sizeToFit()
            button.imageEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0)
            self.navigationItem.titleView = button
        } else {
            let label = UILabel()
            label.text = text
            label.textColor = UIColor.white
            label.sizeToFit()
            self.navigationItem.titleView = label
        }
    }
}
//
//extension UIViewController {
//
//    func lineViewInNavigationBar() {
//        let view = self.navigationController?.navigationBar
//        if let navigation = view {
//            let imageView = MyConfigTool.getLineView(inNavigationBar: navigation)
//            imageView?.image = UIImage(named: "navigation_blue_line")
//        }
//    }
//}

// MARK: - NSMutableAttributedString
extension NSMutableAttributedString {
    
    /// 两种颜色和尺寸的字体
    ///
    /// - Parameters:
    ///   - first: 第一段文字的各种参数
    ///   - second: 第二段文字的各种参数
    /// - Returns: 返回拼接好的文字
   static func differentColorAndSizeString(first : (firstString: NSString, firstColor: UIColor, firstSize: CGFloat), second : (secondString: NSString, secondColor: UIColor, secondSize: CGFloat)) -> NSMutableAttributedString {
        let noteStr = NSMutableAttributedString(string: "\(first.firstString)"+"\(second.secondString)")
        let fStr: NSString = (noteStr.string as NSString?)!
        let fRange: NSRange = (fStr.range(of: first.firstString as String))
        
        let rangeOne = NSRange(location: fRange.location, length: fRange.length)
        noteStr.addAttribute(NSAttributedStringKey.foregroundColor, value: first.firstColor, range: rangeOne)
        
        let sRange: NSRange = (fStr.range(of: second.secondString as String))
        let rangetwo = NSRange(location: sRange.location, length: sRange.length)
        noteStr.addAttribute(NSAttributedStringKey.foregroundColor, value: second.secondColor, range: rangetwo)
        
        noteStr.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: first.firstSize), range: rangeOne)
        noteStr.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: second.secondSize), range: rangetwo)
        
        return noteStr
    }
    
    // 加中划线
   static func strikethrough(str: String) -> NSMutableAttributedString {
        let priceString = NSMutableAttributedString.init(string: str)
        priceString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSNumber.init(value: 1), range: NSRange(location: 0, length: priceString.length))
        
        return priceString
    }
}

// MARK: UIImageView
extension UIImageView {
    
    // 毛玻璃效果
    func blur() {
        let blurViewTag = 500
        var blurView = viewWithTag(blurViewTag) as? UIVisualEffectView
        if blurView == nil {
            let blureffect = UIBlurEffect(style: .extraLight)
            blurView = UIVisualEffectView(effect: blureffect)
            blurView?.tag = blurViewTag
            blurView?.frame.size = self.frame.size
            self.addSubview(blurView!)
        }
    }
    
//    func gaussianBlur() {
//        //获取原始图片
//        let inputImage =  CIImage(image: self.image!)
//        //使用高斯模糊滤镜
//        let filter = CIFilter(name: "CIGaussianBlur")!
//        filter.setValue(inputImage, forKey:kCIInputImageKey)
//        //设置模糊半径值（越大越模糊）
//        filter.setValue(0.8, forKey: kCIInputRadiusKey)
//        let outputCIImage = filter.outputImage!
//        let rect = CGRect(origin: CGPoint.zero, size: (self.image?.size)!)
//        let cgImage = CIContext(options: nil).createCGImage(outputCIImage, from: rect)
//        //显示生成的模糊图片
//        self.image = UIImage(cgImage: cgImage!)
//    }
    
}

/// 检测相机
///
/// - Returns: 是否允许
func checkCamearPermissions() -> Bool {
    let authStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
    if authStatus == AVAuthorizationStatus.denied || authStatus == AVAuthorizationStatus.restricted {
//        TSErrorTipActionsheetView().setWith(title: "相机权限设置", TitleContent: "请为TS+开放相机权限：手机设置-隐私-相机-TS+(打开)", doneButtonTitle: ["去设置", "取消"], complete: { (index) in
//            let url = URL(string: UIApplicationOpenSettingsURLString)
//            if UIApplication.shared.canOpenURL(url!) {
//                UIApplication.shared.openURL(url!)
//            }
//        })
        return false
    } else {
        return true
    }
}

/// 检测相册
///
/// - Returns: 是否允许
func PhotoLibraryPermissions() -> Bool {
    let library: PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
    if library == PHAuthorizationStatus.denied || library == PHAuthorizationStatus.restricted {
//        TSErrorTipActionsheetView().setWith(title: "相册权限设置", TitleContent: "请为TS+开放相册权限：手机设置-隐私-相册-TS+(打开)", doneButtonTitle: ["去设置", "取消"], complete: { (index) in
//            let url = URL(string: UIApplicationOpenSettingsURLString)
//            if UIApplication.shared.canOpenURL(url!) {
//                UIApplication.shared.openURL(url!)
//            }
//        })
        return false
    } else {
        return true
    }
}

// MARK: - String 扩展
extension String {
    /// 将时间格式转换为 date
    func convertToDate() -> NSDate {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(identifier: "GMT")
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let date = dateFormatter.date(from: self)
        return NSDate(timeIntervalSince1970: date!.timeIntervalSince1970)
    }
    
    /// 本地化字符串
    /// - note 请前往 infoPlist.strings 手动添加各语言信息
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }
    
    /// 获取字符宽度
    func sizeOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedStringKey.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.width
    }
    func sizeHOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedStringKey.font: font]
        let rect:CGRect  = self.boundingRect(with: CGSize(width: (ScreenWidth - 70) / 2, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesFontLeading, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 8)], context:nil);
//        let size = self.size(withAttributes: fontAttributes)
        return rect.size.height
    }
    /// 返回自定义属性文本 【字号、行间距】
    ///
    /// - Parameters:
    ///   - string: 原文本
    ///   - font: 字号
    ///   - lineSpacing: 行间距
    ///   - textAlignment: 文本对齐方式
    /// - Returns: 格式化后的属性文本
    static func setStyleAttributeString(string: String, font: UIFont, lineSpacing: CGFloat, textAlignment: NSTextAlignment) -> NSMutableAttributedString {
        let attributeSring = NSMutableAttributedString(string: string)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = textAlignment
        paragraphStyle.lineSpacing = lineSpacing
        attributeSring .addAttributes([NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.font: font], range: NSRange(location: 0, length: CFStringGetLength(string as CFString!)))
        return attributeSring
    }
    
    /// 计算属性文本的高度
    /// 注意： 使用此方法计算高度之前请保证你的属性文本是否设置了正确的属性 否则计算结果不准确概不负责
    ///
    /// - Parameters:
    ///   - attributeString: 待计算的文本
    ///   - maxWidth: 最大宽度
    ///   - maxHeight: 最大高度
    /// - Returns: 文本高度
    static func getAttributeStringHeight(attributeString: NSString, maxWidth: CGFloat, maxHeight: CGFloat) -> CGFloat {
//        attributeString.boundingRect(with: <#T##CGSize#>, options: <#T##NSStringDrawingOptions#>, context: <#T##NSStringDrawingContext?#>)
        let strSize = attributeString.boundingRect(with: CGSize(width: maxWidth, height: maxHeight), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 8)], context:nil)
        
        return strSize.height
    }
    
    /// 获取固定宽度的字符串高度
    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
        return boundingBox.height
    }
    
    // MARK: - 计算字符串宽高
    func heightWithConstrainedWidth(width: CGFloat, height: CGFloat, font: UIFont) -> CGSize {
        let constraintRect = CGSize(width: width, height: height)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
        return boundingBox.size
    }
    
    /// 将字符串数组转为 数组
    /// 例如 "1,2,3" -> [1, 2, 3]
    func convertNumberArray() -> Array<Int>? {
        let stringArray = self.components(separatedBy: ",")
        var uids: Array<Int> = []
        if stringArray.isEmpty {
            return nil
        }
        for string in stringArray {
            if string == "" {
                continue
            }
            uids.append(Int(string)!)
        }
        return uids
    }
    
    func quantityConversion() -> String {
        let value = NSInteger(self)
        switch value! {
        case 0...99:
            return self
        case 100...999:
            return "99+"
        case  1000...:
            let data = String(format: "%lu", value! / 1000)
            return data + "k"
        default:
            return""
        }
    }

}

